/*
 * File     : DefinableClassLoader.java
 * Created  : 17 Apr 2011
 * Revision : $Revision$
 *
 * Copyright © 2006-9 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.WeakHashMap;

import com.googlecode.dni.DirectNativeInterface;
import com.googlecode.dni.InitialisationOption;


/**
 * Class loader implementation that permits loading of arbitrary byte-code.
 *
 * @author Matthew Wilson
 */
public final class DefinableClassLoader extends ClassLoader
{

    private static final boolean DUMP;

    private static final File DUMP_DIR;


    private static final Map< ClassLoader, DefinableClassLoader > LOADERS =
        new WeakHashMap< ClassLoader, DefinableClassLoader >();

    static
    {
        String dir = (String) DirectNativeInterface.getOption( InitialisationOption.DUMP_BYTE_CODE );
        if ( dir == null || dir.isEmpty() )
        {
            DUMP = false;
            DUMP_DIR = null;
        }
        else
        {
            DUMP = true;
            DUMP_DIR = new File( dir );
            DUMP_DIR.mkdirs();
        }
    }


    /**
     * Obtains the {@link DefinableClassLoader} for the given class's class
     * loader.
     *
     * @param clazz
     *            the class
     * @return the class loader
     */
    public static DefinableClassLoader get( final Class< ? > clazz )
    {
        ClassLoader loader = clazz.getClassLoader();
        synchronized ( LOADERS )
        {
            DefinableClassLoader definableClassLoader = LOADERS.get( loader );
            if ( definableClassLoader == null )
            {
                definableClassLoader = new DefinableClassLoader( loader );
                LOADERS.put( loader, definableClassLoader );
            }

            return definableClassLoader;
        }
    }

    private DefinableClassLoader( final ClassLoader parent )
    {
        super( parent );
    }

    /**
     * Defines a class.
     *
     * @param name
     *            the name of the class
     * @param classFile
     *            the bytes forming the class file
     *
     * @return the class
     */
    public Class< ? > define( final String name,
                              final byte[] classFile )
    {
        if ( DUMP )
        {
            File file = new File( DUMP_DIR, name.replace( '.', File.separatorChar ) + ".class" );
            file.getParentFile().mkdirs();

            try
            {
                new FileOutputStream( file ).write( classFile );
            }
            catch ( IOException exception )
            {
                // TODO LOGGER
                exception.printStackTrace();
            }
        }

        return defineClass( name, classFile, 0, classFile.length );
    }

}

